/*
 * @Author: your name
 * @Date: 2020-10-26 14:22:50
 * @LastEditTime: 2020-11-12 17:27:36
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /crowd-funding/src/components/pages/HomePage/homePage.module.js
 */

import {
	homeData,
	dialogData,
	redoundItemData,
	imageData,
	reminderStatus,
	errorData,
	top,
} from './homePage.reducer'

import { put, fork, all, call, takeEvery, select } from 'redux-saga/effects'

import { followProject, initHomeData } from '../../../api/api' // 判断是否是真实数据
import { projectId, shareUrl, ErrorType } from '@/utils/constants'
import { handleNum } from '@/utils/utils' // 判断是否是真实数据
import jdshare from '@jmfe/jm-jdshare'
import { bookCalendar, checkCalendar, removeCalendar } from '@/utils/reminder'
import { get } from 'lodash'
import { isApp } from '@jmfe/jm-common'
import { reportClick } from '@/utils/ping'

// projectId=1854507660
// 预热中项目ID：1831955214
// 众筹中的项目ID：1851940903
// 众筹已结束-众筹成功的项目ID：120211
// 众筹结束--众筹失败项目ID：185194081
// 1851524101

/**
 * @description: 众筹页初始化
 */
function* init() {
	try {
		const res = yield call(initHomeData)

		const { storyPageRes } = res

		const { projectRedoundListDto = [], projectStoryNewDto } = storyPageRes

		storyPageRes.projectRedoundListDto = projectRedoundListDto.map((redoundItem) => {
			if (!redoundItem.canBuy) {
				// 不能购买的情况
				// 剩余数量属性
				redoundItem.surplusCount = 0
				// 购买数量上限属性
				redoundItem.limitCount = 0

				return redoundItem
			}
			// 计算剩余数量
			let surplusCount = 0
			if (redoundItem.limits === 0) {
				surplusCount = Infinity
			} else if (redoundItem.limits - redoundItem.supportNum > 0) {
				surplusCount = redoundItem.limits - redoundItem.supportNum
			} else if (redoundItem.limits - redoundItem.supportNum <= 0) {
				surplusCount = 0
			}

			// 计算购买数量上限
			let limitCount = 0
			if (surplusCount.limits === 0) {
				limitCount = redoundItem.supportLimit
			} else if (surplusCount > 0) {
				limitCount = Math.min(surplusCount, redoundItem.supportLimit)
			} else if (redoundItem.limits - redoundItem.supportNum <= 0) {
				limitCount = 0
			}

			// 剩余数量属性
			redoundItem.surplusCount = surplusCount
			// 购买数量上限属性
			redoundItem.limitCount = limitCount

			return redoundItem
		})

		const asc = (a, b) => {
			// 升序排序
			return a - b
		}
		// 将档位金额存放到档位数组中
		storyPageRes.supportRegion = projectRedoundListDto
			.map((item) => {
				return item.amount
			})
			.sort(asc)
		storyPageRes.supportRegion = storyPageRes.supportRegion.filter((item) => item > 0) // 过滤掉小于0的数据

		storyPageRes.supportRegionL = storyPageRes.supportRegion.length

		if (projectStoryNewDto.buttonStatus === 1) {
			// 设置目标金额为展示金额
			projectStoryNewDto.displayAmount = handleNum(
				projectStoryNewDto.amount < 0 ? 0 : projectStoryNewDto.amount
			)
		}
		if (projectStoryNewDto.buttonStatus !== 1) {
			// 设置已筹金额为展示金额
			projectStoryNewDto.displayAmount = handleNum(
				projectStoryNewDto.collectedAmount < 0 ? 0 : projectStoryNewDto.collectedAmount
			)
		}

		yield put({
			type: 'set:homeData',
			payload: { isLoading: false, storyPageData: storyPageRes },
		}) // 初始数据

		if (projectRedoundListDto.length > 0) {
			const redoundItem = projectRedoundListDto[0]
			// const selected = redoundItem.limits != 0
			yield put({
				type: 'set:redoundItem',
				payload: {
					count: redoundItem.limitCount === 0 && redoundItem.limits !== 0 ? 0 : 1,
					selected: true,
					redoundItem,
				},
			})
		}
		// 处理图片
		yield put({ type: 'handle:image' })
		// 查看提醒组件状态
		if (isApp('jd')) {
			yield put({ type: 'check:reminder' })
			// 初始化分享
			yield put({ type: 'common:share', payload: { shareType: 'setShareInfo' } })
		}

		return ErrorType.SUCCESS_TYPE
	} catch (error) {
		if (error.code === -1) {
			return {
				...error,
				reloadAction: 'reload:homeData',
			}
		}
		return error
	}
}

/**
 * @description:  业务逻辑产生错误的拦截器
 * @param {Function|ErrorType}parm
 */
function* intercepter(arg) {
	// console.log(arg.name)
	try {
		const errorType = yield call(arg)
		yield put({ type: 'set:errorData', payload: errorType })
	} catch (error) {
		yield put({ type: 'set:errorData', payload: ErrorType.NO_DATA_TYPE })
	}
}

/**
 * 获取图片
 */
function* handleImage() {
	try {
		const homeData = yield select((state) => state.homeData)
		const storyPageData = get(homeData, 'storyPageData', {})
		const projectStoryNewDto = get(storyPageData, 'projectStoryNewDto', {})
		const storyDto = get(projectStoryNewDto, 'storyDto', [])
		// 循环取出头部头图type 10001、分享图片 type 10002、预约提醒图片type 10003
		for (let i = 0; i < storyDto.length; i++) {
			const { type } = storyDto[i]
			if (type === '10001') {
				yield put({
					type: 'save:image',
					payload: { headerImage: storyDto[i].picUrlList[0] },
				})
			}
			if (type === '10002') {
				yield put({
					type: 'save:image',
					payload: { shareImage: storyDto[i].picUrlList[0] },
				})
			}
			if (type === '10003') {
				yield put({
					type: 'save:image',
					payload: { reminderImage: storyDto[i].picUrlList[0] },
				})
			}
		}
	} catch (error) {
		console.log('handleImageError:', error)
	}
}

/**
 * 分享
 * @param {payload} shareType: 'setShareInfo' 设置分享， 'callSharePane' 唤起分享面板 默认后者
 */
function* commonShare({ payload }) {
	try {
		const { shareType = 'callSharePane' } = payload
		const homeData = yield select((state) => state.homeData)
		const imageData = yield select((state) => state.imageData)
		const storyPageData = get(homeData, 'storyPageData', {})
		const projectStoryNewDto = get(storyPageData, 'projectStoryNewDto', {})
		const title = get(projectStoryNewDto, 'projectName', '')
		const content = get(projectStoryNewDto, 'projectAdWord', '')
		const shareImage = get(imageData, 'shareImage', '')
		const shareObj = {
			img: shareImage,
			url: shareUrl(),
			title,
			content,
			channel: 'Wxfriends,Wxmoments,Sinaweibo,QQfriends,QQzone,CopyURL',
		}
		console.log('shareObj:', shareObj, shareType)
		if (shareType === 'setShareInfo') {
			jdshare.setShareInfo(shareObj)
		} else {
			jdshare.callSharePane(shareObj)
		}
	} catch (e) {
		console.log('commonShareError:', e)
	}
}

/**
 * 添加日历提醒
 */
function* addReminder() {
	try {
		const homeData = yield select((state) => state.homeData)
		const storyPageData = get(homeData, 'storyPageData', {})
		const projectStoryNewDto = get(storyPageData, 'projectStoryNewDto', {})
		const salesTime = get(projectStoryNewDto, 'salesTime', 0)
		const title = get(projectStoryNewDto, 'projectName', '京东众筹')
		const imageData = yield select((state) => state.imageData)
		const reminderImage = get(imageData, 'reminderImage', '')
		const date = new Date(salesTime)
		const time = parseInt(date.getTime())
		const nTime = parseInt(time - 60000)
		const opt = {
			type: 'JDCROWFUNDING',
			title,
			time,
			nTime,
			url: location.href,
			id: projectId,
			imgUrl: reminderImage,
			tag: '众筹',
		}
		const reminderResult = yield call(bookCalendar, opt)
		const { appointed = false } = reminderResult
		yield put({ type: 'save:reminderStatus', payload: appointed })
		reportClick({
			eventId: 'Mhelp_StoryDetail_RemindResultExpo',
			eventParam: `${projectId}_${appointed ? 1 : 2}`,
		})
		if (appointed) {
			yield put({ type: 'report:reminder' })
		}
	} catch (error) {
		console.log('addReminderError:', error)
	}
}

/**
 * 检查日历提醒
 */
function* checkReminder() {
	try {
		const homeData = yield select((state) => state.homeData)
		const storyPageData = get(homeData, 'storyPageData', {})
		const projectStoryNewDto = get(storyPageData, 'projectStoryNewDto', {})
		const salesTime = get(projectStoryNewDto, 'salesTime', '')
		const date = new Date(salesTime)
		const time = parseInt(date.getTime())
		const opt = {
			type: 'JDCROWFUNDING',
			time,
			id: projectId,
		}
		const calendarStatus = yield call(checkCalendar, opt)
		const { appointed } = calendarStatus
		yield put({ type: 'save:reminderStatus', payload: appointed })
	} catch (error) {
		console.log('addReminderError:', error)
	}
}

/**
 * 删除日历提醒
 */
function* deleteReminder() {
	try {
		const homeData = yield select((state) => state.homeData)
		const storyPageData = get(homeData, 'storyPageData', {})
		const projectStoryNewDto = get(storyPageData, 'projectStoryNewDto', {})
		const salesTime = get(projectStoryNewDto, 'salesTime', '')
		const date = new Date(salesTime)
		const time = parseInt(date.getTime())
		const opt = {
			type: 'JDCROWFUNDING',
			time,
			id: projectId,
		}
		const calendarStatus = yield call(removeCalendar, opt)
		const { appointed = false } = calendarStatus
		if (appointed) {
			// 返回true代表删除成功
			yield put({ type: 'save:reminderStatus', payload: false })
		}
	} catch (error) {
		console.log('addReminderError:', error)
	}
}

/**
 * 上报提醒状态
 */
function* reportReminder() {
	try {
		const res = yield call(followProject)
		const code = get(res, 'code', '-1')
		if (code === 0) {
			console.log('上报提醒状态成功！')
		}
	} catch (error) {
		console.log('reportReminderError:', error)
	}
}

export default {
	reducer: {
		homeData,
		dialogData,
		redoundItemData,
		imageData,
		reminderStatus,
		errorData,
		top,
	},
	*saga() {
		console.log('============')
		yield all([
			fork(intercepter, init),
			takeEvery('reload:homeData', intercepter, init),
			takeEvery('add:reminder', addReminder),
			takeEvery('report:reminder', reportReminder),
			takeEvery('common:share', commonShare),
			takeEvery('handle:image', handleImage),
			takeEvery('check:reminder', checkReminder),
			takeEvery('delete:reminder', deleteReminder),
		])
	},
}
